<template>
  <div class="app">
    <!-- 整体左右布局 -->
    <div class="main-container">
      <!-- 左侧角色列表区域 (2份) -->
      <div v-show="!isLeftPanelCollapsed" class="left-panel">
        <div class="panel-header">
          <h2>角色列表</h2>
        </div>
        <div class="role-list-container">
          <div 
            v-for="role in roles" 
            :key="role.id"
            class="role-item"
            :class="{ active: activeRole?.id === role.id }"
            @click="selectRole(role)"
            @mouseenter="hoveredRoleId = role.id"
            @mouseleave="hoveredRoleId = null"
          >
            <span class="role-name">{{ role.name }}</span>
            <div v-if="hoveredRoleId === role.id && role.id !== 1" class="role-actions">
              <button class="edit-btn" @click.stop="openEditModal(role)">编辑</button>
              <button class="delete-btn" @click.stop="deleteRole(role.id)">删除</button>
            </div>
          </div>
        </div>
        <div class="role-form">
          <button class="add-role-btn" @click="openAddModal">新增角色</button>
        </div>
      </div>

      <!-- 左右切换按钮 -->
      <div class="toggle-button" @click="toggleLeftPanel">
        <div class="toggle-icon">
          <div v-if="isLeftPanelCollapsed" class="arrow-right"></div>
          <div v-else class="arrow-left"></div>
        </div>
      </div>

      <!-- 右侧聊天区域 (8份) -->
      <div class="right-panel">
        <!-- 头部标题 -->
        <div class="app-header">
          <h1 class="app-title">{{ activeRole?.name || 'AI 编程小助手' }}</h1>
          <div class="app-subtitle">帮助您解答编程学习和求职面试相关问题</div>
          <button class="theme-toggle-button" @click="toggleTheme">
            <span v-if="isDarkTheme">☀️</span>
            <span v-else>🌙</span>
          </button>
        </div>

        <!-- 聊天区域 -->
        <div class="chat-container">
          <!-- 消息列表 -->
          <div class="messages-container" ref="messagesContainer">
            <div v-if="messages.length === 0" class="welcome-message">
              <div class="welcome-content">
                <div class="welcome-icon">🤖</div>
                <h2>欢迎使用 {{ activeRole?.name || 'AI 编程小助手' }}</h2>
                <p>我可以帮助您：</p>
                <ul>
                  <li>解答编程技术问题</li>
                  <li>提供代码示例和解释</li>
                  <li>协助求职面试准备</li>
                  <li>分享编程学习建议</li>
                </ul>
                <p>请随时向我提问吧！</p>
              </div>
            </div>

            <!-- 历史消息 -->
            <ChatMessage
              v-for="message in messages"
              :key="message.id"
              :message="message.content"
              :is-user="message.isUser"
              :timestamp="message.timestamp"
            />

            <!-- AI 正在回复的消息 -->
            <div v-if="isAiTyping" class="chat-message ai-message">
              <div class="message-avatar">
                <div class="avatar ai-avatar">AI</div>
              </div>
              <div class="message-content">
                <div class="message-bubble">
                  <div class="ai-typing-content">
                    <div class="ai-response-text message-markdown" v-html="currentAiResponseRendered"></div>
                    <LoadingDots v-if="isStreaming" />
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入框 -->
          <ChatInput
            :disabled="isAiTyping"
            @send-message="sendMessage"
            placeholder="请输入您的编程问题..."
          />
        </div>

        <!-- 连接状态提示 -->
        <div v-if="connectionError" class="connection-error">
          <div class="error-content">
            <span class="error-icon">⚠️</span>
            <span>连接服务器失败，请检查后端服务是否启动</span>
          </div>
        </div>
        
        <!-- 自定义错误提示 -->
        <div v-if="showError" class="custom-error">
          <div class="error-content">
            <span class="error-icon">⚠️</span>
            <span>{{ errorMessage }}</span>
          </div>
        </div>
        
        <!-- 自定义成功提示 -->
        <div v-if="showSuccess" class="custom-success">
          <div class="success-content">
            <span class="success-icon">✅</span>
            <span>{{ successMessage }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增角色弹窗 -->
    <div v-if="showAddModal" class="modal-overlay" @click="closeAddModal">
      <div class="modal-content" @click.stop>
        <h3>新增角色</h3>
        <div class="form-group">
          <label>角色名称:</label>
          <input v-model="newRoleForm.name" type="text" placeholder="请输入角色名称" />
        </div>
        <div class="form-group">
          <label>角色描述:</label>
          <textarea v-model="newRoleForm.persona" placeholder="请输入角色描述"></textarea>
        </div>
        <div class="modal-actions">
          <button class="cancel-btn" @click="closeAddModal">取消</button>
          <button class="confirm-btn" @click="addRoleConfirm">确认</button>
        </div>
      </div>
    </div>

    <!-- 编辑角色弹窗 -->
    <div v-if="showEditModal" class="modal-overlay" @click="closeEditModal">
      <div class="modal-content" @click.stop>
        <h3>编辑角色</h3>
        <div class="form-group">
          <label>角色名称:</label>
          <input v-model="editRoleForm.name" type="text" placeholder="请输入角色名称" />
        </div>
        <div class="form-group">
          <label>角色描述:</label>
          <textarea v-model="editRoleForm.persona" placeholder="请输入角色描述"></textarea>
        </div>
        <div class="modal-actions">
          <button class="cancel-btn" @click="closeEditModal">取消</button>
          <button class="confirm-btn" @click="editRoleConfirm">确认</button>
        </div>
      </div>
    </div>
    
    <!-- 删除角色确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
      <div class="modal-content" @click.stop>
        <h3>确认删除</h3>
        <p>确定要删除这个角色吗？</p>
        <div class="modal-actions">
          <button class="cancel-btn" @click="closeDeleteModal">取消</button>
          <button class="confirm-btn" @click="confirmDeleteRole">确认</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ChatMessage from './components/ChatMessage.vue'
import ChatInput from './components/ChatInput.vue'
import LoadingDots from './components/LoadingDots.vue'
import { chatWithSSE } from './api/chatApi.js'
import { generateMemoryId } from './utils/index.js'
import { marked } from 'marked'
import { getAllRoles, createRole, updateRole, deleteRole } from './api/roleApi.js'

export default {
  name: 'App',
  components: {
    ChatMessage,
    ChatInput,
    LoadingDots
  },
  data() {
    return {
      // 角色相关数据
      roles: [
        { id: 1, name: '默认角色' }
      ],
      activeRole: null,
      hoveredRoleId: null,
      isLeftPanelCollapsed: false,
      
      // 角色表单数据
      showAddModal: false,
      showEditModal: false,
      showDeleteModal: false,
      roleIdToDelete: null,
      newRoleForm: {
        name: '',
        persona: ''
      },
      editRoleForm: {
        id: null,
        name: '',
        persona: ''
      },
      
      // 主题相关数据
      isDarkTheme: false,
      
      // 聊天相关数据
      messages: [],
      memoryId: null,
      isAiTyping: false,
      isStreaming: false,
      currentAiResponse: '',
      currentEventSource: null,
      connectionError: false,
      
      // 错误提示相关
      showError: false,
      errorMessage: '',
      
      // 成功提示相关
      showSuccess: false,
      successMessage: ''
    }
  },
  computed: {
    currentAiResponseRendered() {
      if (!this.currentAiResponse) return ''
      // 配置marked选项
      marked.setOptions({
        breaks: true, // 支持换行
        gfm: true, // 支持GitHub风格的Markdown
        sanitize: false, // 不过滤HTML（根据需要可以开启）
        highlight: function(code, lang) {
          // 可以在这里添加代码高亮功能
          return code
        }
      })
      return marked(this.currentAiResponse)
    }
  },
  methods: {
    // 角色相关方法
    async loadRoles() {
      try {
        const roles = await getAllRoles()
        this.roles = roles
        // 如果还没有选中角色，默认选择第一个
        if (!this.activeRole && this.roles.length > 0) {
          this.activeRole = this.roles[0]
        }
      } catch (error) {
        console.error('加载角色列表失败:', error)
      }
    },
    
    selectRole(role) {
      this.activeRole = role
      // 切换角色时清空聊天记录
      this.messages = []
      this.memoryId = generateMemoryId()
    },
    
    toggleLeftPanel() {
      this.isLeftPanelCollapsed = !this.isLeftPanelCollapsed
    },
    
    // 新增角色弹窗相关方法
    openAddModal() {
      this.newRoleForm = { name: '', persona: '' }
      this.showAddModal = true
    },
    
    closeAddModal() {
      this.showAddModal = false
      this.newRoleForm = { name: '', persona: '' }
    },
    
    async addRoleConfirm() {
      if (!this.newRoleForm.name.trim()) {
        this.showError = true
        this.errorMessage = '请输入角色名称'
        
        // 3秒后自动隐藏错误提示
        setTimeout(() => {
          this.showError = false
          this.errorMessage = ''
        }, 3000)
        return
      }
      
      try {
        const roleData = {
          name: this.newRoleForm.name.trim(),
          persona: this.newRoleForm.persona.trim()
        }
        
        const newRole = await createRole(roleData)
        this.roles.push(newRole)
        this.closeAddModal()
        
        // 显示成功提示
        this.showSuccess = true
        this.successMessage = '新建角色成功'
        
        // 3秒后自动隐藏成功提示
        setTimeout(() => {
          this.showSuccess = false
          this.successMessage = ''
        }, 3000)
      } catch (error) {
        console.error('创建角色失败:', error)
        this.showError = true
        this.errorMessage = '创建角色失败，请重试'
        
        // 3秒后自动隐藏错误提示
        setTimeout(() => {
          this.showError = false
          this.errorMessage = ''
        }, 3000)
      }
    },
    
    // 编辑角色弹窗相关方法
    openEditModal(role) {
      this.editRoleForm = {
        id: role.id,
        name: role.name,
        persona: role.persona || ''
      }
      this.showEditModal = true
    },
    
    closeEditModal() {
      this.showEditModal = false
      this.editRoleForm = { id: null, name: '', persona: '' }
    },
    
    async editRoleConfirm() {
      if (!this.editRoleForm.name.trim()) {
        this.showError = true
        this.errorMessage = '请输入角色名称'
        
        // 3秒后自动隐藏错误提示
        setTimeout(() => {
          this.showError = false
          this.errorMessage = ''
        }, 3000)
        return
      }
      
      try {
        const roleData = {
          name: this.editRoleForm.name.trim(),
          persona: this.editRoleForm.persona.trim()
        }
        
        const updatedRole = await updateRole(this.editRoleForm.id, roleData)
        
        // 更新角色列表中的角色
        const index = this.roles.findIndex(r => r.id === this.editRoleForm.id)
        if (index !== -1) {
          this.roles.splice(index, 1, updatedRole)
        }
        
        // 如果正在编辑的是当前选中的角色，也要更新
        if (this.activeRole && this.activeRole.id === this.editRoleForm.id) {
          this.activeRole = updatedRole
        }
        
        this.closeEditModal()
        
        // 显示成功提示
        this.showSuccess = true
        this.successMessage = '角色更新成功'
        
        // 3秒后自动隐藏成功提示
        setTimeout(() => {
          this.showSuccess = false
          this.successMessage = ''
        }, 3000)
      } catch (error) {
        console.error('更新角色失败:', error)
        this.showError = true
        this.errorMessage = '更新角色失败，请重试'
        
        // 3秒后自动隐藏错误提示
        setTimeout(() => {
          this.showError = false
          this.errorMessage = ''
        }, 3000)
      }
    },
    
    // 删除角色 - 打开确认弹窗
    deleteRole(roleId) {
      if (roleId === 1) {
        this.showError = true
        this.errorMessage = '默认角色不能删除'
        
        // 3秒后自动隐藏错误提示
        setTimeout(() => {
          this.showError = false
          this.errorMessage = ''
        }, 3000)
        return
      }
      
      // 打开删除确认弹窗
      this.roleIdToDelete = roleId
      this.showDeleteModal = true
    },
    
    // 关闭删除弹窗
    closeDeleteModal() {
      this.showDeleteModal = false
      this.roleIdToDelete = null
    },
    
    // 确认删除角色
    async confirmDeleteRole() {
      if (!this.roleIdToDelete) return
      
      try {
        await deleteRole(this.roleIdToDelete)
        
        // 从角色列表中移除
        const index = this.roles.findIndex(r => r.id === this.roleIdToDelete)
        if (index !== -1) {
          this.roles.splice(index, 1)
        }
        
        // 如果删除的是当前选中的角色，切换到第一个角色
        if (this.activeRole && this.activeRole.id === this.roleIdToDelete) {
          this.activeRole = this.roles.length > 0 ? this.roles[0] : null
          this.messages = []
          this.memoryId = generateMemoryId()
        }
        
        // 关闭弹窗
        this.closeDeleteModal()
        
        // 显示成功提示
        this.showSuccess = true
        this.successMessage = '角色删除成功'
        
        // 3秒后自动隐藏成功提示
        setTimeout(() => {
          this.showSuccess = false
          this.successMessage = ''
        }, 3000)
      } catch (error) {
        console.error('删除角色失败:', error)
        this.showError = true
        this.errorMessage = '删除角色失败，请重试'
        this.closeDeleteModal()
        
        // 3秒后自动隐藏错误提示
        setTimeout(() => {
          this.showError = false
          this.errorMessage = ''
        }, 3000)
      }
    },
    
    toggleTheme() {
      this.isDarkTheme = !this.isDarkTheme
      if (this.isDarkTheme) {
        document.body.classList.add('dark-theme')
        localStorage.setItem('theme', 'dark')
      } else {
        document.body.classList.remove('dark-theme')
        localStorage.setItem('theme', 'light')
      }
    },
    
    // 聊天相关方法
    sendMessage(message) {
      // 添加用户消息
      this.addMessage(message, true)
      
      // 开始AI回复
      this.startAiResponse(message)
    },
    
    addMessage(content, isUser = false) {
      const message = {
        id: Date.now() + Math.random(),
        content,
        isUser,
        timestamp: new Date()
      }
      this.messages.push(message)
      this.scrollToBottom()
    },
    
    startAiResponse(userMessage) {
      this.isAiTyping = true
      this.isStreaming = true
      this.currentAiResponse = ''
      this.connectionError = false
      
      // 关闭之前的连接
      if (this.currentEventSource) {
        this.currentEventSource.close()
      }
      
      // 开始SSE连接
      this.currentEventSource = chatWithSSE(
        this.memoryId,
        userMessage,
        this.handleAiMessage,
        this.handleAiError,
        this.handleAiClose
      )
    },
    
    handleAiMessage(data) {
      // 确保所有类型的数据都能正确添加到响应中
      this.currentAiResponse += (data !== undefined && data !== null) ? data : ''
      this.scrollToBottom()
    },
    
    handleAiError(error) {
      console.error('AI 回复出错:', error)
      this.connectionError = true
      this.finishAiResponse()
      
      // 5秒后自动隐藏错误提示
      setTimeout(() => {
        this.connectionError = false
      }, 5000)
    },
    
    handleAiClose() {
      this.finishAiResponse()
    },
    
    finishAiResponse() {
      this.isStreaming = false
      
      // 如果有内容，添加到消息列表
      if (this.currentAiResponse !== undefined && this.currentAiResponse !== null && this.currentAiResponse.trim()) {
        this.addMessage(this.currentAiResponse.trim(), false)
      }
      
      // 重置状态
      this.isAiTyping = false
      this.currentAiResponse = ''
      
      // 重置连接错误状态（确保正常结束时清除错误提示）
      this.connectionError = false
      
      // 关闭连接
      if (this.currentEventSource) {
        this.currentEventSource.close()
        this.currentEventSource = null
      }
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },
    
    initializeChat() {
      // 加载角色列表
      this.loadRoles()
      
      // 默认选择第一个角色
      if (this.roles.length > 0) {
        this.activeRole = this.roles[0]
      }
      this.memoryId = generateMemoryId()
      console.log('聊天室ID:', this.memoryId)
    }
  },
  
  mounted() {
    this.initializeChat()
    
    // 检查用户主题偏好
    const savedTheme = localStorage.getItem('theme')
    if (savedTheme === 'dark') {
      this.isDarkTheme = true
      document.body.classList.add('dark-theme')
    } else if (savedTheme === 'light') {
      this.isDarkTheme = false
      document.body.classList.remove('dark-theme')
    } else {
      // 如果没有保存的偏好，使用系统偏好
      const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
      this.isDarkTheme = prefersDark
      if (prefersDark) {
        document.body.classList.add('dark-theme')
      }
    }
  },
  
  beforeUnmount() {
    // 组件销毁前关闭连接
    if (this.currentEventSource) {
      this.currentEventSource.close()
    }
  }
}
</script>

<style scoped>
.app {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 左侧角色列表区域 (2份) */
.left-panel {
  width: 20%;
  background-color: #f5f5f5;
  border-right: 1px solid #ddd;
  display: flex;
  flex-direction: column;
  padding: 20px;
  transition: all 0.3s ease;
}

.panel-header h2 {
  margin-top: 0;
  text-align: center;
  color: #333;
}

.role-list-container {
  flex: 1;
  overflow-y: auto;
  margin: 20px 0;
}

.role-item {
  padding: 15px 10px;
  margin-bottom: 10px;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.role-item:hover {
  background-color: #e9e9e9;
}

.role-item.active {
  background-color: #409eff;
  color: white;
}

.role-name {
  text-align: center;
  flex: 1;
}

.role-actions {
  position: absolute;
  right: 10px;
  display: flex;
  gap: 5px;
}

.role-actions button {
  padding: 2px 8px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.edit-btn {
  background-color: #409eff;
  color: white;
}

.delete-btn {
  background-color: #f56c6c;
  color: white;
}

.role-form {
  display: flex;
  justify-content: center;
  padding-top: 10px;
  border-top: 1px solid #ddd;
  width: 100%;
}

.add-role-btn {
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  width: 100%;
}

.add-role-btn:hover {
  background-color: #337ecc;
}

/* 左右切换按钮 */
.toggle-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 26px;
  background: #ffffff;
  cursor: pointer;
  user-select: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: none;
  position: relative;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.toggle-button:hover {
  background: #f8f9fa;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.toggle-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.arrow-left,
.arrow-right {
  width: 8px;
  height: 8px;
  border-top: 2px solid #495057;
  border-right: 2px solid #495057;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.arrow-left {
  transform: rotate(-135deg);
}

.arrow-right {
  transform: rotate(45deg);
}

.toggle-button:hover .arrow-left,
.toggle-button:hover .arrow-right {
  border-color: #007bff;
}

.toggle-button:hover .arrow-left {
  transform: scale(1.15) rotate(-135deg);
}

.toggle-button:hover .arrow-right {
  transform: scale(1.15) rotate(45deg);
}

/* 右侧聊天区域 (8份) */
.right-panel {
  width: 80%;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.app-header {
  background-color: #fff;
  padding: 20px;
  border-bottom: 1px solid #e1e5e9;
  text-align: center;
  position: relative;
}

.theme-toggle-button {
  position: absolute;
  top: 20px;
  right: 20px;
  background: transparent;
  border: none;
  font-size: 20px;
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.theme-toggle-button:hover {
  background-color: #f0f0f0;
}

.app-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.app-subtitle {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
}

.welcome-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.welcome-content {
  text-align: center;
  max-width: 400px;
  color: #666;
}

.welcome-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.welcome-content h2 {
  font-size: 20px;
  margin-bottom: 15px;
  color: #333;
}

.welcome-content p {
  margin-bottom: 10px;
  line-height: 1.5;
}

.welcome-content ul {
  text-align: left;
  margin: 15px 0;
}

.welcome-content li {
  margin-bottom: 5px;
}

/* AI 正在回复时的消息样式 */
.chat-message {
  display: flex;
  margin-bottom: 20px;
  padding: 0 20px;
}

.ai-message {
  justify-content: flex-start;
  flex-direction: row;
}

.message-avatar {
  display: flex;
  align-items: flex-start;
  margin: 0 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  color: white;
}

.ai-avatar {
  background-color: #6c757d;
}

/* 用户头像使用蓝色主题 */
.chat-message:not(.ai-message) .avatar {
  background-color: #4285f4;
}

.message-content {
  max-width: 70%;
  min-width: 100px;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  word-wrap: break-word;
  word-break: break-word;
  background-color: #f1f3f4;
  color: #333;
  border-bottom-left-radius: 4px;
}

/* 用户消息使用蓝色主题 */
.chat-message:not(.ai-message) .message-bubble {
  background-color: #4285f4;
  color: white;
}

/* AI消息使用灰色主题 */
.ai-message .message-bubble {
  background-color: #f1f3f4;
  color: #333;
}

.ai-typing-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.ai-response-text {
  font-size: 14px;
  line-height: 1.5;
}

/* AI实时回复的Markdown样式 */
.ai-response-text.message-markdown h1,
.ai-response-text.message-markdown h2,
.ai-response-text.message-markdown h3,
.ai-response-text.message-markdown h4,
.ai-response-text.message-markdown h5,
.ai-response-text.message-markdown h6 {
  margin: 0.5em 0;
  font-weight: bold;
}

.ai-response-text.message-markdown h1 { font-size: 1.5em; }
.ai-response-text.message-markdown h2 { font-size: 1.3em; }
.ai-response-text.message-markdown h3 { font-size: 1.2em; }
.ai-response-text.message-markdown h4 { font-size: 1.1em; }
.ai-response-text.message-markdown h5 { font-size: 1em; }
.ai-response-text.message-markdown h6 { font-size: 0.9em; }

.ai-response-text.message-markdown p {
  margin: 0.5em 0;
}

.ai-response-text.message-markdown ul,
.ai-response-text.message-markdown ol {
  margin: 0.5em 0;
  padding-left: 1.5em;
}

.ai-response-text.message-markdown li {
  margin: 0.2em 0;
}

.ai-response-text.message-markdown code {
  background-color: rgba(0, 0, 0, 0.1);
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.9em;
}

.ai-response-text.message-markdown pre {
  background-color: rgba(0, 0, 0, 0.1);
  padding: 1em;
  border-radius: 5px;
  overflow-x: auto;
  margin: 0.5em 0;
}

.ai-response-text.message-markdown pre code {
  background-color: transparent;
  padding: 0;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.9em;
}

.ai-response-text.message-markdown blockquote {
  border-left: 4px solid #ccc;
  padding-left: 1em;
  margin: 0.5em 0;
  font-style: italic;
  color: #666;
}

.ai-response-text.message-markdown a {
  color: #007bff;
  text-decoration: underline;
}

.ai-response-text.message-markdown table {
  border-collapse: collapse;
  width: 100%;
  margin: 0.5em 0;
}

.ai-response-text.message-markdown th,
.ai-response-text.message-markdown td {
  border: 1px solid #ddd;
  padding: 0.5em;
  text-align: left;
}

.ai-response-text.message-markdown th {
  background-color: #f2f2f2;
  font-weight: bold;
}

.ai-response-text.message-markdown hr {
  border: none;
  border-top: 1px solid #ddd;
  margin: 1em 0;
}

.connection-error {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #ff4444;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  z-index: 1000;
  animation: slideDown 0.3s ease-out;
}

.custom-error {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #ff4444;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  z-index: 1000;
  animation: slideDown 0.3s ease-out;
}

.custom-success {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #4caf50;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  z-index: 1000;
  animation: slideDown 0.3s ease-out;
}

.error-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.success-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.error-icon {
  font-size: 16px;
}

@keyframes slideDown {
  from {
    transform: translateX(-50%) translateY(-100%);
    opacity: 0;
  }
  to {
    transform: translateX(-50%) translateY(0);
    opacity: 1;
  }
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
  max-width: 90%;
}

.modal-content h3 {
  margin-top: 0;
  text-align: center;
}

.modal-content p {
  text-align: center;
  margin: 20px 0;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-group textarea {
  min-height: 100px;
  resize: vertical;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.modal-actions button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

.confirm-btn {
  background-color: #409eff;
  color: white;
}

.confirm-btn:hover {
  background-color: #337ecc;
}

/* 深色主题样式 */
body.dark-theme {
  background-color: #1a1a1a;
  color: #e0e0e0;
}

body.dark-theme .app-header {
  background-color: #2d2d2d;
  border-bottom: 1px solid #444;
}

body.dark-theme .app-title {
  color: #fff;
}

body.dark-theme .app-subtitle {
  color: #aaa;
}

body.dark-theme .left-panel {
  background-color: #2d2d2d;
  border-right: 1px solid #444;
}

body.dark-theme .panel-header h2 {
  color: #fff;
}

body.dark-theme .role-item {
  background-color: #3d3d3d;
  border: 1px solid #555;
  color: #e0e0e0;
}

body.dark-theme .role-item:hover {
  background-color: #4d4d4d;
}

body.dark-theme .role-item.active {
  background-color: #1a73e8;
}

body.dark-theme .role-form input {
  background-color: #3d3d3d;
  border: 1px solid #555;
  color: #e0e0e0;
}

body.dark-theme .role-form input:focus {
  border-color: #1a73e8;
  box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
}

body.dark-theme .add-role-btn {
  background-color: #1a73e8;
}

body.dark-theme .add-role-btn:hover {
  background-color: #0d62c9;
}

body.dark-theme .toggle-button {
  background: #3d3d3d;
}

body.dark-theme .toggle-button:hover {
  background: #4d4d4d;
}

body.dark-theme .arrow-left,
body.dark-theme .arrow-right {
  border-color: #e0e0e0;
}

body.dark-theme .toggle-button:hover .arrow-left,
body.dark-theme .toggle-button:hover .arrow-right {
  border-color: #1a73e8;
}

/* 用户消息使用蓝色主题 */
body.dark-theme .chat-message:not(.ai-message) .message-bubble {
  background-color: #1a73e8;
  color: white;
}

/* AI消息使用灰色主题 */
body.dark-theme .ai-message .message-bubble {
  background-color: #3d3d3d;
  color: #e0e0e0;
}

body.dark-theme .welcome-content {
  color: #aaa;
}

body.dark-theme .welcome-content h2 {
  color: #fff;
}

body.dark-theme .ai-response-text.message-markdown code {
  background-color: rgba(255, 255, 255, 0.1);
}

body.dark-theme .ai-response-text.message-markdown pre {
  background-color: rgba(255, 255, 255, 0.1);
}

body.dark-theme .ai-response-text.message-markdown blockquote {
  border-left: 4px solid #555;
  color: #aaa;
}

body.dark-theme .ai-response-text.message-markdown a {
  color: #4d90fe;
}

body.dark-theme .ai-response-text.message-markdown th {
  background-color: #333;
}

body.dark-theme .ai-response-text.message-markdown td,
body.dark-theme .ai-response-text.message-markdown th {
  border: 1px solid #555;
}

body.dark-theme .ai-response-text.message-markdown hr {
  border-top: 1px solid #555;
}

body.dark-theme .messages-container::-webkit-scrollbar-track {
  background: #2d2d2d;
}

body.dark-theme .messages-container::-webkit-scrollbar-thumb {
  background: #555;
}

body.dark-theme .messages-container::-webkit-scrollbar-thumb:hover {
  background: #777;
}

body.dark-theme .custom-error {
  background-color: #ff4444;
  color: white;
}

body.dark-theme .custom-success {
  background-color: #4caf50;
  color: white;
}

body.dark-theme .theme-toggle-button:hover {
  background-color: #4d4d4d;
}

body.dark-theme .modal-content {
  background-color: #2d2d2d;
  color: #e0e0e0;
}

body.dark-theme .form-group input,
body.dark-theme .form-group textarea {
  background-color: #3d3d3d;
  border: 1px solid #555;
  color: #e0e0e0;
}

body.dark-theme .cancel-btn {
  background-color: #3d3d3d;
  color: #e0e0e0;
}

body.dark-theme .cancel-btn:hover {
  background-color: #4d4d4d;
}

body.dark-theme .modal-content p {
  color: #e0e0e0;
}

body.dark-theme .ai-avatar {
  background-color: #6c757d;
}

/* 用户头像使用蓝色主题 */
body.dark-theme .chat-message:not(.ai-message) .avatar {
  background-color: #1a73e8;
}

@media (max-width: 768px) {
  .left-panel {
    width: 30%;
    padding: 10px;
  }
  
  .right-panel {
    width: 70%;
  }
  
  .app-header {
    padding: 15px;
  }
  
  .app-title {
    font-size: 20px;
  }
  
  .messages-container {
    padding: 15px 0;
  }
  
  .welcome-content {
    padding: 0 10px;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .chat-message {
    padding: 0 10px;
  }
}
</style>